package ${pkg};

import java.util.Date;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.collect.Lists;
import ${servicePkg}.${clzName}Service;
import com.klnst.constant.Constant;
import com.klnst.core.web.BaseController;
import com.klnst.core.utils.JsonDateValueProcessor;
import com.klnst.core.utils.SystemUtil;
import com.klnst.domain.Catalogue;
import com.klnst.domain.Organization;
import com.klnst.domain.TableColumn;
import com.klnst.domain.SysOperator;
import com.klnst.domain.SysQryLog;
import com.klnst.core.form.ConditionEntity;
import com.klnst.service.CatalogueService;
import com.klnst.service.OrganizationService;
import com.klnst.service.TableColumnService;
import com.klnst.service.SysQryLogService;
/**
 * 
 * @ClassName: ${tableName?cap_first}_Controller 
 * @Description: ${tableComment} 
 * @author ilaotou@qq.com
 * This class is generatored by AutoTool
 */
@Controller
@RequestMapping(value = "/${tableName?substring(0,tableName?index_of('_',0) )}/${prefix}/${org}/${tableName}")
public class ${tableName?cap_first}_Controller extends BaseController{
	
	@Autowired
	public ${clzName}Service ${clzName?uncap_first}Service;
	
	@Autowired
	public TableColumnService tableColumnService;
	
	@Autowired
	public OrganizationService organizationService;
	
	
	@Autowired
	public CatalogueService catalogueService;
	
	@Autowired
	public SysQryLogService sysQryLogService;
	
	/**
	@RequestMapping(value = "search",params="_m=init")
	public String list(@RequestParam String _tb,Model model,ServletRequest request) {
		model.addAttribute("_tb", _tb);
		return "bm/${tableName?substring(0,tableName?index_of('_',0) )}/${tableName}_list";
	} 
    */
        
    /**
	 * 
	 * @Title: list 
	 * @Description: 初始化查询页面
	 * @param _tb 表名称
	 * @param id 日志ID
	 * @param model
	 * @param request
	 * @return
	 * @return String    返回类型 
	 * @throws
	 */
	@RequestMapping(value = "search",params="_m=init")
	public String list(@RequestParam String _tb,@RequestParam String id,Model model,ServletRequest request) {
		String flag=flag=StringUtils.isBlank(request.getParameter("flag"))?"":request.getParameter("flag");
		Organization org=null;
		String old_table="";//不带年月的表称
		if(StringUtils.isNotBlank(_tb)){
			old_table=StringUtils.split(_tb, "_").length>2?StringUtils.substringBeforeLast(_tb, "_"):_tb;
		}
		SysQryLog sysQryLog = sysQryLogService.findUniqueById(id);
		model.addAttribute("_tb", _tb);
		model.addAttribute("flag", flag);
		model.addAttribute("sysQryLog", sysQryLog);
		model.addAttribute("id", id);
		return"bm/${tableName?substring(0,tableName?index_of('_',0) )}/${(tableName?substring(tableName?index_of('_',0)+1 ))?substring(0,(tableName?substring(tableName?index_of('_',0)+1 ))?index_of('_',0) )}/${org}/${tableName}_list";
	} 
	@RequestMapping(value = "search",params="_m=query")
	@ResponseBody
	public String paging4DynamicTblName(@RequestParam("page") int page,@RequestParam("pagesize") int pagesize,@RequestParam("_tb") String _tb,@RequestParam("_logid") String _logid,ServletRequest request) throws Exception {
//		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		SysOperator user = (SysOperator) WebUtils.getSessionAttribute((HttpServletRequest) request,Constant.SESSION_USER_KEY);
		List<ConditionEntity> columns=Lists.newArrayList();
		String _con = request.getParameter("_con");
		if(StringUtils.isNotBlank(_con)&&!_con.equals("[]")){
			try{
				columns = JSON.parseArray(_con, ConditionEntity.class);  
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}
		columns.add(new ConditionEntity("sys_log_id","EQ",_logid));
		PageBounds pageBounds = new PageBounds(page, pagesize,null,false);
        List list = ${clzName?uncap_first}Service.paging4DynamicTblName(user,_tb,columns, pageBounds);
        long cnt=${clzName?uncap_first}Service.pagingCount4DynamicTblName(user,_tb,columns);
        JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
        String json=SystemUtil.createPagingJson(JSONArray.fromObject(list,jsonConfig).toString(), String.valueOf(cnt));
		return json;
	} 
	
	@RequestMapping(value = "search",params="_m=condition_init")
	public String conditionInit(@RequestParam String _tb,Model model,ServletRequest request) {
		List<TableColumn> list = tableColumnService.findByTblName(_tb);
		List ll = Lists.newArrayList();
		for(TableColumn c : list){
			ll.add(new Dropdwon4TableField(c.getFieldName(),c.getCluComment()));
		}
		String ss = JSON.toJSON(list).toString();
		model.addAttribute("dw_field", JSON.toJSON(list));
		return "bm/${tableName?substring(0,tableName?index_of('_',0) )}/${(tableName?substring(tableName?index_of('_',0)+1 ))?substring(0,(tableName?substring(tableName?index_of('_',0)+1 ))?index_of('_',0) )}/${tableName}_list_condition";
	} 
	
	/**
	 * 
	 * @Title: traceLogInit 
	 * @Description: 记录跟踪初始化查询页面 
	 * @param _tb
	 * @param id
	 * @param model
	 * @param request
	 * @return
	 * @return String    返回类型 
	 * @throws
	 */
	@RequestMapping(value = "tracelog",params="_m=init")
	public String traceLogInit(@RequestParam String _tb,@RequestParam String id,Model model,ServletRequest request) {
		String flag=flag=StringUtils.isBlank(request.getParameter("flag"))?"":request.getParameter("flag");
		String[] tbs = StringUtils.split(_tb, "_");
		if(tbs.length>2){
			_tb = StringUtils.substringBeforeLast(_tb, "_");
		}
		model.addAttribute("_tb", "log_"+_tb);
		model.addAttribute("flag", flag);
		model.addAttribute("prefix", "${prefix}");
		model.addAttribute("org", "${org}");
		model.addAttribute("id", id);
		return"bm/log/trace_list";
	} 
	/**
	 * 
	 * @Title: traceLog 
	 * @Description: 记录跟踪查询
	 * @param page
	 * @param pagesize
	 * @param _tb
	 * @param _logid
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 * @return String    返回类型 
	 * @throws
	 */
	@RequestMapping(value = "tracelog",params="_m=query")
	public @ResponseBody String traceLog(@RequestParam("page") int page,@RequestParam("pagesize") int pagesize,@RequestParam String _tb,@RequestParam("_logid") String _logid,Model model,ServletRequest request) throws Exception {
		PageBounds pageBounds = new PageBounds(page, pagesize,null,true);
        List list = ${clzName?uncap_first}Service.traceByLogId(_logid,pageBounds);
        PageList pg = (PageList)list;
        JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
        String json=SystemUtil.createPagingJson(JSONArray.fromObject(list,jsonConfig).toString(), String.valueOf(pg.getPaginator().getTotalCount()));
		return json;
	} 
	
}
